package com.rxtxdemo.rxtxdemo.demo;

import com.rxtxdemo.rxtxdemo.applicationevent.publish.IComService;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Data
public class MyLister implements SerialPortEventListener {

    private IComService comService;

    private ThreadPoolTaskExecutor poolTaskExecutor1;

    private SerialPort com;

    private int conut = 0;

    public static int sum = 0;

    //标记有无新数据
    boolean hasData = false;

    //存储可以发送的指令
    private StringBuffer buf = new StringBuffer();

    @SneakyThrows
    @Override
    /**
     * 数据接收的监听处理函数
     */
    public void serialEvent(SerialPortEvent serialPortEvent) {
        if (serialPortEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            conut++;
            //数据通知
            SerialPortutil serialPortutil = SerialPortutil.getSerialPortutil();

            String str = serialPortutil.readComm(com);

            //处理指令数据不完整
            log.info("的位置 : [{}]", str.indexOf("0", 0));
            if (str.indexOf("0", 0) == -1) {
                buf.append(str);
                log.info("数据不完整：[{}]", buf.toString());
            } else {
                poolTaskExecutor1.execute(() -> {
                    buf.append(str);
                    comStatePush(buf.toString());
                    buf.delete(0, buf.length());
                    log.info("指令数据已清理：[{}]", buf.toString());
                });
            }

            log.info("====================== sum : [{}]", sum);
        }

    }

    /**
     * 接收串口状态，将状态信息推送到执行策略类
     */
    public void comStatePush(String order) {
        log.info("接收串口状态, 主线程id：[{}], 主线程名称：[{}]", Thread.currentThread().getId(), Thread.currentThread().getName());
        Map<String, String> conMap = new ConcurrentHashMap<>(8);
        conMap.put("order", order);
        comService.register(conMap);
    }
}
